package ywpt.web.interceptor;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import ywpt.components.acegi.domain.User;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class CookieInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// 取得请求相关的ActionContext实例
		// 取得请求相关的ActionContext实例
		ActionContext ctx = invocation.getInvocationContext();
		HttpServletRequest request= (HttpServletRequest) ctx.get(StrutsStatics.HTTP_REQUEST);   

		if ( request == null ) {
	/*		System.out.println("request is null");*/
			return "login";
		}
		
/*		System.out.println("CookieInterceptor has  request!!!");*/
		Cookie cookies[]=request.getCookies();
		Cookie sCookie=null; 
		String svalue=null; 
		String sname=null; 
		for(int i=0;i<cookies.length-1;i++) {   //用一个循环语句遍历刚才建立的Cookie对象数组 
			sCookie=cookies[i];					 //取出数组中的一个Cookie对象 
			sname=sCookie.getName(); 	//取得这个Cookie的名字
/*			System.out.println("sCookie.getName() =" + sCookie.getName() );
			System.out.println("sCookie.getValue()" +  sCookie.getValue() );*/
			if (sname.equals("username")) {
				svalue=sCookie.getValue();       //取得这个Cookie的内容 
			}
		}

		if ( svalue != null ) {
/*			System.out.println("CookieInterceptor has  user:  "+ svalue );*/
			
			return invocation.invoke();
		} 

	/*	System.out.println("CookieInterceptor has no  user");*/
		ctx.put("tip", "你还没有登录");
		return "login";
	}

}
